package net.color4me.app.farmere.action;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.color4me.app.farmere.entity.FarmUser;
import net.color4me.app.farmere.server.EMF;
import net.color4me.app.farmere.server.FarmerClient;

@SuppressWarnings("serial")
public class FarmTask2Servlet extends HttpServlet {
	@Override
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		EntityManager em = EMF.get().createEntityManager();
		String result = "";
		Query q = em
				.createQuery("SELECT p FROM net.color4me.app.farmere.entity.FarmUser p");
		List<FarmUser> users = q.getResultList();

		for (FarmUser u : users) {
			FarmerClient famer = new FarmerClient();
			int nowMin = Calendar.MINUTE;
			System.out.println(u.getUser());
			if (u.getCookieStr() != null && u.getLink() != null
					&& !u.getCookieStr().equals("") && !u.getLink().equals("")) {
				if ((u.getId().intValue() % nowMin) % 2 != 1) {
					FarmUser newfarmer = famer.login(u.getUser(), u
							.getPassword());
					String page = famer.farmWork(newfarmer);
					famer.logout(page);
					result += page;
				}
			}

		}
		req.setAttribute("msg", result);

		try {
			resp.setContentType("text/html; charset=UTF-8");
			resp.setCharacterEncoding("UTF-8");
			req.getRequestDispatcher("/jsp/task.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
